<template>
  <view class="detail-container">
    <!-- 顶部标题 -->
    <view class="header">
      <text class="title">{{ t('prescription.title') }}</text>
    </view>

    <!-- 加载中 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">{{ t('common.loading') }}</text>
    </view>

    <!-- 空态 -->
    <view v-else-if="!detail" class="empty-state">
      <text class="empty-text">{{ t('order_list.noData') }}</text>
    </view>

    <!-- 内容 -->
    <view v-else class="content">
      <!-- 基本信息 -->
      <view class="card">
        <view class="row">
          <text class="label">{{ t('order_detail.prescriptionNumber') }}</text>
          <text class="value">{{ detail.outpatient_no }}</text>
        </view>
        <view class="row">
          <text class="label">{{ t('order_detail.patientName') }}</text>
          <text class="value">{{ patientName }}</text>
        </view>
        <view class="row">
          <text class="label">{{ t('order_list.createTime') }}</text>
          <text class="value">{{ detail.create_datetime || '-' }}</text>
        </view>
        <view class="card-actions">
          <button class="consent-btn" @click="viewConsent">{{ t('medical.view_consent') }}</button>
        </view>
      </view>

      <!-- 诊断/辨证 -->
      <view class="card">
        <view class="section-title">{{ t('prescription.clinical_diagnosis') }}</view>
        <view class="row">
          <text class="label">{{ t('prescription.diagnosis') }}</text>
          <text class="value">{{ displayDiagnosis }}</text>
        </view>
        <view class="row">
          <text class="label">{{ t('prescription.syndrome_differentiation') }}</text>
          <text class="value">{{ detail.details?.dialectic || '-' }}</text>
        </view>
      </view>

      

      <!-- 药材清单 -->
      <view class="card">
        <view class="section-title">{{ t('prescription.select_medicine') }}</view>
        <view v-if="Array.isArray(detail.medicines) && detail.medicines.length" class="medicine-list">
          <view v-for="(m, idx) in detail.medicines" :key="m.id || idx" class="medicine-item">
            <view class="medicine-name">{{ m.drug_info?.drugs_name || '-' }}</view>
            <view class="medicine-meta">
              <text>{{ t('prescription.quantity') }}: {{ m.dose }}{{ m.drug_info?.drugs_unit || 'g' }}</text>
              <text v-if="m.decoction_method" class="method">{{ t('prescription.decoction') }}: {{ m.decoction_method }}</text>
            </view>
          </view>
        </view>
        <view v-else class="empty-state small">
          <text class="empty-text">{{ t('medicine.no_medicines') }}</text>
        </view>
      </view>

      <!-- 药量计算（只读） -->
      <view class="card dosage-calculator">
        <view class="section-header">
          <text class="calculator-title">{{ t('prescription.dosage_calculator') }}</text>
        </view>
        <view class="calculator-content">
          <view class="dosage-info">
            <text class="value-chip">{{ totalPerDoseGrams }}</text>
            <text class="usage-unit">{{ t('prescription.total_per_dose') }}</text>
            <text class="value-chip">{{ detail.details?.dosage_count ?? '-' }}</text>
            <text class="usage-unit">{{ t('prescription.dose') }}</text>
            <text class="total-weight">{{ t('prescription.total_weight') }}{{ totalTotalWeightGrams }}g</text>
          </view>
        </view>
      </view>

      <!-- 用法用量（对齐开方页样式，详情只读） -->
      <view class="card usage-dosage-section">
        <view class="section-header">
          <!-- <text class="section-icon">💊</text> -->
          <text class="calculator-title">{{ t('prescription.usage_dosage') }}</text>
        </view>
        <view class="usage-content">
          <view class="usage-row">
            <text class="required-mark">*</text>
            <text class="value-chip">{{ detail.details?.usage_days ?? '-' }}</text>
            <text class="usage-unit">{{ t('prescription.days') }}</text>
            <text class="value-chip">{{ detail.details?.usage_doses ?? '-' }}</text>
            <text class="usage-unit">{{ t('prescription.doses_per_day') }}</text>
            <text class="required-mark">*</text>
            <text class="usage-text">{{ t('prescription.times_per_dose') }}</text>
            <text class="value-chip">{{ detail.details?.usage_times ?? '-' }}</text>
            <text class="usage-text">{{ t('prescription.times') }}</text>
            <text class="required-mark">*</text>
            <text class="usage-text">{{ t('prescription.amount_per_time') }}</text>
            <text class="value-chip">{{ detail.details?.usage_amount ?? '-' }}</text>
            <text class="usage-unit">{{ t('prescription.ml') }}</text>
          </view>

          <!-- 剂数展示 -->
          <!-- <view class="dose-row">
            <text class="dose-label">{{ t('prescription.dose') }}</text>
            <text class="dose-value">{{ detail.details?.dosage_count ?? '-' }}</text>
          </view> -->

          <!-- 备注信息（只读） -->
          <view class="remarks-content">
            <view class="remarks-header">
              <!-- <text class="remarks-icon">📝</text> -->
              <text class="remarks-title">{{ t('prescription.remarks_title') }}</text>
            </view>
            <view class="remarks-display readonly">
              <text class="remarks-text">{{ detail.details?.usage_notes || '-' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 用药医嘱 -->
      <view class="card">
        <view class="section-title">{{ t('prescription.medication_instructions') }}</view>
        <view class="row">
          <text class="label">{{ t('prescription.medication_description') }}</text>
          <text class="value">{{ detail.details?.medication_instructions || '-' }}</text>
        </view>
        <view class="row">
          <text class="label">{{ t('prescription.medication_time') }}</text>
          <text class="value">{{ detail.details?.medication_time || '-' }}</text>
        </view>
        <view class="row">
          <text class="label">{{ t('prescription.medication_contraindications') }}</text>
          <text class="value">{{ detail.details?.medication_contraindications || '-' }}</text>
        </view>
      </view>

    </view>
  </view>
  
</template>

<script>
import { useI18n } from 'vue-i18n'
import { getTreatmentRecordChineseMedicineDetail } from '@/api/medical.js'

export default {
  data() {
    return {
      loading: false,
      detail: null,
      outpatientNo: ''
    }
  },
  setup() {
    const { t } = useI18n()
    return { t }
  },
  computed: {
    patientName() {
      try {
        const last = this.detail?.patient_info?.last_name || ''
        const first = this.detail?.patient_info?.first_name || ''
        const name = `${last}${first}`.trim()
        return name || this.t('order_list.unknownUser')
      } catch (e) {
        return this.t('order_list.unknownUser')
      }
    },
    displayDiagnosis() {
      const d = (this.detail?.details?.diagnosis || '').trim()
      const s = (this.detail?.details?.dialectic || '').trim()
      return d || s || '-'
    },
    // 每剂总重量（g），一位小数
    totalPerDoseGrams() {
      try {
        const list = Array.isArray(this.detail?.medicines) ? this.detail.medicines : []
        const total = list.reduce((sum, m) => sum + (parseFloat(m?.dose) || 0), 0)
        return total.toFixed(1)
      } catch (e) {
        return '0.0'
      }
    },
    // 总重量（g）= 每剂总重量 * 剂数
    totalTotalWeightGrams() {
      try {
        const perDose = parseFloat(this.totalPerDoseGrams) || 0
        const doses = parseFloat(this.detail?.details?.dosage_count) || 0
        return (perDose * doses).toFixed(1)
      } catch (e) {
        return '0.0'
      }
    }
  },
  onLoad(options) {
    this.outpatientNo = options?.outpatient_no || ''
    this.fetchDetail()
  },
  methods: {
    async fetchDetail() {
      if (!this.outpatientNo) {
        this.detail = null
        return
      }
      if (this.loading) return
      this.loading = true
      try {
        const res = await getTreatmentRecordChineseMedicineDetail(this.outpatientNo)
        if (res && (res.code === 200 || res.success)) {
          this.detail = res.result
        } else {
          this.detail = null
          uni.showToast({ title: res?.message || this.t('common.request_failed'), icon: 'none' })
        }
      } catch (error) {
        this.detail = null
        uni.showToast({ title: this.t('common.request_failed'), icon: 'none' })
      } finally {
        this.loading = false
      }
    }
    ,
    viewConsent() {
      const consentId = this.detail?.consent_id
      if (!consentId) {
        uni.showToast({ title: this.t('medical.not_filled'), icon: 'none' })
        return
      }
      // 根据实际路由跳转知情说明书页面（这里暂用患者信息页占位）
      uni.navigateTo({
        url: `/pages/medicine/consentForm?consent_id=${consentId}`
      })
    }
  }
}
</script>

<style scoped>
.detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20rpx;
}

.header {
  padding: 24rpx 20rpx 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.loading-state,
.empty-state {
  margin: 20rpx;
  padding: 100rpx 20rpx;
  background: #fff;
  border-radius: 12rpx;
  text-align: center;
}

.empty-state.small {
  padding: 40rpx 20rpx;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999;
}

.content {
  padding: 0 20rpx 20rpx 20rpx;
}

.card {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
}
.card-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12rpx;
}
.consent-btn {
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  height: 64rpx;
  line-height: 64rpx;
  padding: 0 24rpx;
  font-size: 26rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
}

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.row:last-child {
  border-bottom: none;
}

.label {
  font-size: 26rpx;
  color: #666;
  margin-right: 16rpx;
}

.value {
  font-size: 28rpx;
  color: #333;
  text-align: right;
  flex: 1;
}

.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.grid-item {
  background: #f9fafb;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 16rpx;
}

.grid-label {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.grid-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.medicine-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.medicine-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx;
  background: #f9fafb;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
}

.medicine-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.medicine-meta {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  text-align: right;
  color: #666;
  font-size: 24rpx;
}

.medicine-meta .method {
  color: #007aff;
}

/* 对齐开方页的用法用量视觉，仅做只读展示 */
.usage-dosage-section .section-header {
  display: flex;
  align-items: center;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #e9ecef;
}
.usage-dosage-section .section-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
}
.usage-dosage-section .calculator-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}
.usage-content {
  margin-top: 16rpx;
}
.usage-row {
  display: flex;
  align-items: center;
  gap: 6rpx;
  flex-wrap: wrap;
}
.required-mark {
  color: #e74c3c;
  font-size: 24rpx;
  font-weight: bold;
}
.usage-unit {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
}
.usage-text {
  font-size: 24rpx;
  color: #666;
}
.value-chip {
  padding: 6rpx 16rpx;
  background: #f5f5f5;
  color: #333;
  border: 1rpx solid #e9ecef;
  border-radius: 16rpx;
  font-size: 24rpx;
  min-width: 60rpx;
  text-align: center;
}
.dose-row {
  margin-top: 12rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}
.dose-label {
  font-size: 24rpx;
  color: #666;
}
.dose-value {
  font-size: 26rpx;
  color: #333;
  background: #fff;
  padding: 6rpx 12rpx;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
}
.remarks-content {
  margin-top: 24rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #d4edda;
}
.remarks-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 16rpx;
}
.remarks-icon {
  font-size: 24rpx;
}
.remarks-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}
.remarks-display.readonly {
  display: flex;
  justify-content: center;
}
.remarks-text {
  font-size: 26rpx;
  color: #333;
  background: #f5f5f5;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  border: 1rpx solid #e9ecef;
  max-width: 100%;
  word-break: break-all;
}

/* 药量计算样式（对齐整体灰系） */
.dosage-calculator .section-header {
  display: flex;
  align-items: center;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #e9ecef;
}
.dosage-calculator .calculator-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}
.calculator-content {
  display: flex;
  justify-content: center;
  padding-top: 16rpx;
}
.dosage-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex-wrap: wrap;
  justify-content: center;
}
.total-weight {
  font-size: 26rpx;
  color: #333;
  background: #fff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  border: 1rpx solid #e9ecef;
}
</style>
